<template>
	<view class="page-section page-section-gap map-container">
		<map style="width: 100%; height: 100vh;" :latitude="latitude" :longitude="longitude" :scale="scale"
			@markertap="markertap">
			<map-marker v-for="(cluster, index) in clusters" :id="index" :latitude="cluster.latitude"
				:longitude="cluster.longitude" :iconPath="getClusterIconPath(cluster.count)" :width="36" :height="36"
				:data="cluster">
				<view slot="content">
					<view>{{ cluster.count }}</view>
				</view>
			</map-marker>
		</map>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				TotalPoints: [], //所有的点
				clusters: [], //聚合后的点
				latitude: 37.524957, //纬度
				longitude: 111.146425, //经度
				scale: 11, //缩放级别
				maxClusterRadius: 80, //最大聚合半径，单位像素
				clusterIconPath: '/static/icon/location_cluster_64.png', //聚合图标路径
			}
		},
		onShow() {
			this.loadPoints(); //请求机构信息
		},
		methods: {
			loadPoints() {
				// 使用 QueryRTInfoList() 方法请求数据并处理
				// ...
				this.TotalPoints = response.rows;
				this.clusterPoints();
			},
			clusterPoints() {
				let clusters = [];
				let clusterId = 0;
				let idToCluster = {};

				for (let i = 0; i < this.TotalPoints.length; i++) {
					let point = this.TotalPoints[i];
					let clustered = false;

					for (const cluster of Object.values(idToCluster)) {
						if (this.getDistance(point, cluster) < this.maxClusterRadius) {
							clustered = true;
							cluster.pointCount++;
							cluster.latitude = (cluster.latitude * (cluster.pointCount - 1) + point.latitude) / cluster
								.pointCount;
							cluster.longitude = (cluster.longitude * (cluster.pointCount - 1) + point.longitude) / cluster
								.pointCount;
							break;
						}
					}

					if (!clustered) {
						let cluster = {
							id: clusterId++,
							latitude: point.latitude,
							longitude: point.longitude,
							pointCount: 1,
						};
						clusters.push(cluster);
						idToCluster[cluster.id] = cluster;
					}
				}

				this.clusters = clusters;
			},
			getDistance(point1, point2) {
				let lat1 = point1.latitude;
				let lng1 = point1.longitude;
				let lat2 = point2.latitude;
				let lng2 = point2.longitude;
				let R = 6371; // 地球半径，单位千米
				let dLat = (lat2 - lat1) * Math.PI / 180;
				let dLng = (lng2 - lng1) * Math.PI / 180;
				let a = Math.sin(dLat / 2) * Math.sin(dLat / 2) + Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math
					.PI / 180) * Math.sin(dLng / 2) * Math.sin(dLng / 2);
				let c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
				let d = R * c;
				return d * 1000; // 单位米
			},
			markertap(e) {
				let cluster = e.markerId !== undefined ? e.markerId : e.currentTarget.dataset;
				console.log("===你点击了标记点===", cluster)
			},
			getClusterIconPath(count) {
				if (count === 1) {
					return '/static/icon/location_red_64.png';
				} else {
					return this.clusterIconPath;
				}
			},
		}
	}
</script>